package com.haruhi.bot.job;

import com.haruhi.bot.job.thread.ExecuteCMDThread;
import com.haruhi.bot.service.BotManage;
import com.haruhi.bot.utils.CMDUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 定时检查真寻是否宕机
 */
@Component
@Slf4j
public class CheckBotStatusJob {

    @Value("${bot.port}")
    private String port;

    @Autowired
    private BotManage botManage;

    private static ScheduledExecutorService pool = Executors.newScheduledThreadPool(1);
    // 30分钟执行一次
    private static long period = 1000 * 60 * 30;
    private static long initialDelay = 0;
    public void start(){
        pool.scheduleAtFixedRate(new CheckBotStatusJob.JobTask(port,botManage),initialDelay,period, TimeUnit.MILLISECONDS);
    }

    public static class JobTask implements Runnable{

        private String port;
        private BotManage botManage;
        public JobTask(String port,BotManage botManage){
            this.port = port;
            this.botManage = botManage;
        }

        @Override
        public void run() {
            log.info("开始检测真寻状态...port:{}",port);
            String pid = CMDUtil.getPID(port);
            if(pid == null){
                log.info("真寻状态:宕机");
                if(CMDUtil.isLinux()){
                    botManage.startBot();

                    for (int i = 0; i < 4; i++) {
                        try {
                            Thread.sleep(45 * 1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        String pid1 = CMDUtil.getPID(port);
                        if(pid1 != null){
                            log.info("真寻唤醒成功");
                            break;
                        }

                    }
                    log.info("唤醒失败");

                }else{
                    log.info("检测系统异常:当期非linux环境");
                }
            }else{
                log.info("真寻状态:启动");
            }

        }
    }
}
